package com.rem.concurrency.juc.my7Unsafe;

import cn.hutool.core.util.RandomUtil;

import java.util.concurrent.CopyOnWriteArrayList;

/**
 * java.util.ConcurrentModificationException 并发修改异常
 *
 * @author Rem
 * @date 2021-03-08
 */

public class ListTest {

    public static void main(String[] args) {

        /**
         * 并发下 ArrayList不是一个安全的集合
         * 解决方法：
         * 1、List<String> list = new Vector<>();  //synchroniceed 关键字
         * 2、List<String> list = Collections.synchronizedList(new ArrayList<>());
         * 3、List<String> list = new CopyOnWriteArrayList<>()；  //transient volatile 修饰 Lock显示锁
         */

        //List<String> list = new ArrayList<>();
        //List<String> list = new Vector<>();
        //  List<String> list = Collections.synchronizedList(new ArrayList<>());

        CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
        for (int i = 1; i <= 10; i++) {
            new Thread(() -> {
                list.add(RandomUtil.randomString(4));
                System.out.println(list);
            }, String.valueOf(i)).start();
        }

    }
}
